package model

import (
	"database/sql"
	"fmt"
	"strings"
	"time"

	"github.com/tal-tech/go-zero/core/stores/builder"
	"github.com/tal-tech/go-zero/core/stores/cache"
	"github.com/tal-tech/go-zero/core/stores/sqlc"
	"github.com/tal-tech/go-zero/core/stores/sqlx"
	"github.com/tal-tech/go-zero/core/stringx"
)

var (
	searchFieldNames          = builder.RawFieldNames(&Search{})
	searchRows                = strings.Join(searchFieldNames, ",")
	searchRowsExpectAutoSet   = strings.Join(stringx.Remove(searchFieldNames, "`id`", "`create_time`", "`update_time`"), ",")
	searchRowsWithPlaceHolder = strings.Join(stringx.Remove(searchFieldNames, "`id`", "`create_time`", "`update_time`"), "=?,") + "=?"

	cacheSearchIdPrefix = "cache:search:id:"
)

type (
	SearchModel interface {
		Insert(data *Search) (sql.Result, error)
		FindOne(id int64) (*Search, error)
		FindOneByUserIdAndName(id int64, name string) (*Search, error)
		Update(data *Search) error
		Delete(id int64) error
	}

	defaultSearchModel struct {
		sqlc.CachedConn
		table string
	}

	Search struct {
		Id         int64     `db:"id"`
		UserId     int64     `db:"user_id"` // 用户id
		Name       string    `db:"name"`    // 名称
		Count      int64     `db:"count"`   // 查询次数
		CreateTime time.Time `db:"create_time"`
		UpdateTime time.Time `db:"update_time"`
	}
)

func NewSearchModel(conn sqlx.SqlConn, c cache.CacheConf) SearchModel {
	return &defaultSearchModel{
		CachedConn: sqlc.NewConn(conn, c),
		table:      "`search`",
	}
}

func (m *defaultSearchModel) Insert(data *Search) (sql.Result, error) {
	query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?)", m.table, searchRowsExpectAutoSet)
	ret, err := m.ExecNoCache(query, data.UserId, data.Name, data.Count)

	return ret, err
}

func (m *defaultSearchModel) FindOne(id int64) (*Search, error) {
	searchIdKey := fmt.Sprintf("%s%v", cacheSearchIdPrefix, id)
	var resp Search
	err := m.QueryRow(&resp, searchIdKey, func(conn sqlx.SqlConn, v interface{}) error {
		query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", searchRows, m.table)
		return conn.QueryRow(v, query, id)
	})
	switch err {
	case nil:
		return &resp, nil
	case sqlc.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}

func (m *defaultSearchModel) FindOneByUserIdAndName(userId int64, name string) (*Search, error) {
	var resp Search

	query := fmt.Sprintf("select %s from %s where `id` = '%v' and `name` = '%v' limit 1", searchRows, m.table, userId, name)
	err := m.QueryRowNoCache(&resp, query)

	switch err {
	case nil:
		return &resp, nil
	case sqlc.ErrNotFound:
		return nil, ErrNotFound
	default:
		return nil, err
	}
}

func (m *defaultSearchModel) Update(data *Search) error {
	searchIdKey := fmt.Sprintf("%s%v", cacheSearchIdPrefix, data.Id)
	_, err := m.Exec(func(conn sqlx.SqlConn) (result sql.Result, err error) {
		query := fmt.Sprintf("update %s set %s where `id` = ?", m.table, searchRowsWithPlaceHolder)
		return conn.Exec(query, data.UserId, data.Name, data.Count, data.Id)
	}, searchIdKey)
	return err
}

func (m *defaultSearchModel) Delete(id int64) error {

	searchIdKey := fmt.Sprintf("%s%v", cacheSearchIdPrefix, id)
	_, err := m.Exec(func(conn sqlx.SqlConn) (result sql.Result, err error) {
		query := fmt.Sprintf("delete from %s where `id` = ?", m.table)
		return conn.Exec(query, id)
	}, searchIdKey)
	return err
}

func (m *defaultSearchModel) formatPrimary(primary interface{}) string {
	return fmt.Sprintf("%s%v", cacheSearchIdPrefix, primary)
}

func (m *defaultSearchModel) queryPrimary(conn sqlx.SqlConn, v, primary interface{}) error {
	query := fmt.Sprintf("select %s from %s where `id` = ? limit 1", searchRows, m.table)
	return conn.QueryRow(v, query, primary)
}
